#pragma once

#include <iostream>
#include <signal.h>
#include <string>
#include <functional>

#include "Socket.hpp"

using func_t = std::function<std::string(std::string &package)>;

class TcpServer
{
public:
    TcpServer()
    {
    }

    TcpServer(uint16_t port, func_t callback) : _port(port), _callback(callback)
    {
    }

    void InitServer()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        lg(INFO, "init server .... done");
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = _listensock.Accept(&clientip, &clientport);
            if (sockfd < 0)
                continue;
            lg(INFO, "accept a new link, sockfd: %d, clientip: %s, clientport: %d", sockfd, clientip.c_str(), clientport);
            if (fork() == 0)
            {
                _listensock.Close();
                std::string inbuffer_stream;
                // 提供计算服务
                while (true)
                {
                    char buffer[1280];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;
                        lg(DEBUG, "debug:\n%s", inbuffer_stream.c_str());

                        while (true)
                        {
                            std::string info = _callback(inbuffer_stream);
                            if (info.empty())
                                break;
                            lg(DEBUG, "debug:response:\n%s", info.c_str());
                            lg(DEBUG, "debug:\n%s", inbuffer_stream.c_str());

                            write(sockfd, info.c_str(), info.size());
                        }

                        // std::string info = _callback(inbuffer_stream);
                        // // 判空
                        // if (info.empty())
                        //     continue;
                        // // 写入数据
                        // write(sockfd, info.c_str(), info.size());
                    }
                    else if (n == 0)
                        break;
                    else
                        break;
                }

                exit(0);
            }
            close(sockfd);
        }
    }

    ~TcpServer()
    {
    }

public:
    int _port;
    Sock _listensock;
    func_t _callback;
};